package com.tiantian.quanminxiu.utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by admin on 2016/11/17.
 */

public class TimerTaskUtils {

    private Timer timer = null;
    private static boolean flag = false;

    private static TimerTaskUtils mybTimeTask = null;

    private TimerTaskUtils(){

    }
    //单例模式，保持这个对象
    public static TimerTaskUtils getInstance(){
        if (mybTimeTask == null || flag ) {
            //当flag == true时，为了解决，timer.cancel()后，重新创建一个timer
            mybTimeTask = new TimerTaskUtils();
            if (flag) {
                flag = false;
            }
        }
        return mybTimeTask;
    }

    public void start(long time,TimerTask task) {

        if (timer == null){
            timer = new Timer();
        } else {
            //从此计时器的任务队列中移除所有已取消的任务。
            timer.purge();
        }

        if(task!=null){
            timer.schedule(task, 0, time);
        }
    }

    public void destroyed(){
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
        flag = true;
    }
}
